<?php
class ControllerModuleCart extends Controller {
	public function index() {
		$this->language->load('module/cart');

		if (isset($this->request->get['remove'])) {
			$this->cart->remove($this->request->get['remove']);

			unset($this->session->data['vouchers'][$this->request->get['remove']]);
		}

		// Totals
		$this->load->model('setting/extension');
		$total_data = array();
		$total = 0;
		$taxes = $this->cart->getTaxes();

		// Display prices
		if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
			$sort_order = array();

			$results = $this->model_setting_extension->getExtensions('total');

			foreach ($results as $key => $value) {
				$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
			}

			array_multisort($sort_order, SORT_ASC, $results);

			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
					$this->load->model('total/' . $result['code']);

					$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
				}

				$sort_order = array();

				foreach ($total_data as $key => $value) {
					$sort_order[$key] = $value['sort_order'];
				}

				array_multisort($sort_order, SORT_ASC, $total_data);
			}
		}

		$this->data['totals'] = $total_data;

		$this->data['heading_title'] = $this->language->get('heading_title');
		$this->data['text_items'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total));
		$this->data['text_empty'] = $this->language->get('text_empty');
		$this->data['text_cart'] = $this->language->get('text_cart');
		$this->data['text_checkout'] = $this->language->get('text_checkout');
		$this->data['text_payment_profile'] = $this->language->get('text_payment_profile');
		$this->data['button_remove'] = $this->language->get('button_remove');

		$this->load->model('tool/image');
		$this->data['products'] = array();
		foreach ($this->cart->getProducts() as $product) {
			if ($product['image']) {
				$image = $this->model_tool_image->resize($product['image'], $this->config->get('config_image_cart_width'), $this->config->get('config_image_cart_height'));
			} else {
				$image = '';
			}

			$option_data = array();

			foreach ($product['option'] as $option) {
				if ($option['type'] != 'file') {
					$value = $option['option_value'];
				} else {
					$filename = $this->encryption->decrypt($option['option_value']);

					$value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
				}

				$option_data[] = array(
					'name'  => $option['name'],
					'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value),
					'type'  => $option['type']
				);
			}

			// Display prices
			if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
				$price = $this->currency->format($product['price']);
			} else {
				$price = false;
			}

			// Display prices
			if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
				$total = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']);
			} else {
				$total = false;
			}

			$this->data['products'][] = array(
				'key'       => $product['key'],
				'thumb'     => $image,
				'name'      => $product['name'],
				'model'     => $product['model'],
				'option'    => $option_data,
				'quantity'  => $product['quantity'],
				'price'     => $price,
				'total'     => $total,
				'href'      => $this->url->link('product/product', 'product_id=' . $product['product_id']),
				'recurring' => $product['recurring'],
				'profile'   => $product['profile_name'],
                'desc'      => $product['description'],
			);
		}

		// Gift Voucher
		$this->data['vouchers'] = array();
		if (!empty($this->session->data['vouchers'])) {
			foreach ($this->session->data['vouchers'] as $key => $voucher) {
				$this->data['vouchers'][] = array(
					'key'         => $key,
					'description' => $voucher['description'],
					'amount'      => $this->currency->format($voucher['amount'])
				);
			}
		}

		$this->data['cart'] = $this->url->link('checkout/cart');
		//$this->data['checkout'] = $this->url->link('checkout/checkout', '', 'SSL');
        $this->data['checkout'] = $this->url->link('checkout/onestep', '', 'SSL');
        $this->data['remove'] = $this->url->link('module/cart/remove');

        $this->data['template'] = 'catalog/view/theme/'.$this->config->get('config_template').'/';
        $this->data['subtotal'] = $this->currency->format($this->cart->getSubTotal());
        $this->data['checkout_mode'] = (isset($this->request->get['route']) && $this->request->get['route'] == 'checkout/onestep') ? 1 : 0;

        if ($this->isMobileEnabled()) {
            $this->data['redirect'] = true;
        }

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/cart.tpl')) {
			$this->template = $this->config->get('config_template') . '/template/module/cart.tpl';
		} else {
			$this->template = 'default/template/module/cart.tpl';
		}

		//$this->response->setOutput($this->render());
        return $this->render();
	}

    public function add() {
        $this->language->load('module/cart');
        $json = array();

        if (isset($this->request->post['product_id'])) {
            $product_id = $this->request->post['product_id'];
        } else {
            $product_id = 0;
        }

        $this->load->model('catalog/product');
        $product_info = $this->model_catalog_product->getProduct($product_id);
        if ($product_info) {
            if (isset($this->request->post['quantity'])) {
                $quantity = $this->request->post['quantity'];
            } else {
                $quantity = 1;
            }

            if (isset($this->request->post['option'])) {
                $option = array_filter($this->request->post['option']);
            } else {
                $option = array();
            }

            if (isset($this->request->post['profile_id'])) {
                $profile_id = $this->request->post['profile_id'];
            } else {
                $profile_id = 0;
            }

            $product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);
            foreach ($product_options as $product_option) {
                if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
                    $json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
                }
            }

            $profiles = $this->model_catalog_product->getProfiles($product_info['product_id']);
            if ($profiles) {
                $profile_ids = array();

                foreach ($profiles as $profile) {
                    $profile_ids[] = $profile['profile_id'];
                }

                if (!in_array($profile_id, $profile_ids)) {
                    $json['error']['profile'] = $this->language->get('error_profile_required');
                }
            }

            if (!$json) {
                $this->cart->add($this->request->post['product_id'], $quantity, $option, $profile_id);

                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);

                $json['success'] = true;
                $json['product'] = 'Antal varer: '.($this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0));
                $json['total'] = 'Total: '.$this->currency->format($this->cart->getSubTotal());
                $json['total_items'] = $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0);
                $json['html'] = $this->index();
            } else {
                $json['success'] = false;
                $json['redirect'] = str_replace('&amp;', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']));
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function update(){
        $json = array();

        if (!empty($this->request->post['quantity'])) {
            //$subtotal_before = $this->cart->getSubTotal();

            foreach ($this->request->post['quantity'] as $key => $value) {
                $this->cart->update($key, $value);
            }

            if (isset($this->request->post['checkout_mode']) && $this->request->post['checkout_mode']) {
                //$subtotal_after = $this->cart->getSubTotal();
                $redirect = true; //($subtotal_before >= 200 && $subtotal_after < 200) || ($subtotal_before < 200 && $subtotal_after >= 200);
                $json['checkout_mode'] = $redirect ? $this->url->link('checkout/onestep', '', 'SSL') : '';
            }
            else{
                $json['checkout_mode'] = '';

                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);
                unset($this->session->data['reward']);
            }

            $json['success'] = true;
            $json['product'] = 'Antal varer: '.($this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0));
            $json['total'] = 'Total: '.$this->currency->format($this->cart->getSubTotal());
            $json['html'] = $this->index();
            $json['redirect'] = $this->url->link('checkout/cart', '', 'SSL');
        }
        else {
            $json['success'] = false;
        }

        $this->response->setOutput(json_encode($json));
    }

    public function remove(){
        $json = array();

        if (isset($this->request->get['remove'])) {
            //$subtotal_before = $this->cart->getSubTotal();

            $this->cart->remove($this->request->get['remove']);
            unset($this->session->data['vouchers'][$this->request->get['remove']]);

            if (isset($this->request->get['checkout_mode']) && $this->request->get['checkout_mode']) {
                //$subtotal_after = $this->cart->getSubTotal();
                $redirect = true; //($subtotal_before >= 200 && $subtotal_after < 200) || ($subtotal_before < 200 && $subtotal_after >= 200);
                $json['checkout_mode'] = $redirect ? $this->url->link('checkout/onestep', '', 'SSL') : '';
            }
            else{
                $json['checkout_mode'] = '';

                unset($this->session->data['shipping_method']);
                unset($this->session->data['shipping_methods']);
                unset($this->session->data['payment_method']);
                unset($this->session->data['payment_methods']);
                unset($this->session->data['reward']);
            }

            $json['success'] = true;
            $json['product'] = 'Antal varer: '.($this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0));
            $json['total'] = 'Total: '.$this->currency->format($this->cart->getSubTotal());
            $json['html'] = $this->index();
            $json['redirect'] = $this->url->link('checkout/cart', '', 'SSL');
        }
        else {
            $json['success'] = false;
        }

        $this->response->setOutput(json_encode($json));
    }
}
?>